<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">


  <link rel="icon" type="image/png" sizes="16x16" href="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/avatar.jpg">

<link rel="stylesheet" href="/next/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.3/css/all.min.css" integrity="sha256-2H3fkXt6FEmrReK448mDVGKb3WW2ZZw35gI7vqHOE4Y=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css" integrity="sha256-Vzbj7sDDS/woiFS3uNKo8eIuni59rjyNGtXfstRzStA=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"cnhuazhu.gitee.io","root":"/next/","images":"/next/images","scheme":"Mist","version":"8.6.1","exturl":false,"sidebar":{"position":"left","Muse | Mist":320,"display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":true,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/next/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/next/js/config.js"></script>
<meta name="description" content="本文将介绍Promise的使用">
<meta property="og:type" content="article">
<meta property="og:title" content="Vue学习-Promise">
<meta property="og:url" content="https://cnhuazhu.gitee.io/next/2021/08/17/Vue/Vue%E5%AD%A6%E4%B9%A0-Promise/index.html">
<meta property="og:site_name" content="花猪のBlog">
<meta property="og:description" content="本文将介绍Promise的使用">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/CNhuazhu/tu-chuang1/raw/master/img-blog/Promise-异步请求成功.png">
<meta property="og:image" content="https://gitee.com/CNhuazhu/tu-chuang1/raw/master/img-blog/Promise-链式编程.png">
<meta property="article:published_time" content="2021-08-17T07:08:43.000Z">
<meta property="article:modified_time" content="2021-08-20T10:36:29.886Z">
<meta property="article:author" content="花猪">
<meta property="article:tag" content="Vue">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/CNhuazhu/tu-chuang1/raw/master/img-blog/Promise-异步请求成功.png">


<link rel="canonical" href="https://cnhuazhu.gitee.io/next/2021/08/17/Vue/Vue%E5%AD%A6%E4%B9%A0-Promise/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://cnhuazhu.gitee.io/next/2021/08/17/Vue/Vue%E5%AD%A6%E4%B9%A0-Promise/","path":"2021/08/17/Vue/Vue学习-Promise/","title":"Vue学习-Promise"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Vue学习-Promise | 花猪のBlog</title>
  




  <noscript>
    <link rel="stylesheet" href="/next/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/next/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">花猪のBlog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-主站"><a href="https://cnhuazhu.top/" rel="noopener" target="_blank"><i class="fas fa-chevron-right fa-fw"></i>主站</a></li>
        <li class="menu-item menu-item-home"><a href="/next/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
        <li class="menu-item menu-item-tags"><a href="/next/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">14</span></a></li>
        <li class="menu-item menu-item-categories"><a href="/next/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">8</span></a></li>
        <li class="menu-item menu-item-archives"><a href="/next/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">53</span></a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%89%8D%E8%A8%80"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Promise"><span class="nav-number">2.</span> <span class="nav-text">Promise</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8"><span class="nav-number">2.1.</span> <span class="nav-text">基本使用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%9B%E5%BB%BA"><span class="nav-number">2.1.1.</span> <span class="nav-text">创建</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%89%E7%A7%8D%E7%8A%B6%E6%80%81"><span class="nav-number">2.1.2.</span> <span class="nav-text">三种状态</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8"><span class="nav-number">2.1.3.</span> <span class="nav-text">使用</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Promise%E7%9A%84%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8"><span class="nav-number">2.2.</span> <span class="nav-text">Promise的链式调用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%93%BE%E5%BC%8F%E8%B0%83%E7%94%A8"><span class="nav-number">2.2.1.</span> <span class="nav-text">链式调用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%AE%80%E5%86%99%E4%B8%80"><span class="nav-number">2.2.2.</span> <span class="nav-text">简写一</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%AE%80%E5%86%99%E4%BA%8C"><span class="nav-number">2.2.3.</span> <span class="nav-text">简写二</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%90%8E%E8%AE%B0"><span class="nav-number">3.</span> <span class="nav-text">后记</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-overview">
            <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="花猪"
      src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/avatar.jpg">
  <p class="site-author-name" itemprop="name">花猪</p>
  <div class="site-description" itemprop="description">为了获得不同的阅读体验，建立此分站。<br>（可在导航栏搜索想要查看的文章）<br><br>本站主题：NEXT 8.6.1</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/next/archives/">
        
          <span class="site-state-item-count">53</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/next/categories/">
          
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/next/tags/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/CNhuazhu" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;CNhuazhu" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>



          </div>
        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/CNhuazhu" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://cnhuazhu.gitee.io/next/2021/08/17/Vue/Vue%E5%AD%A6%E4%B9%A0-Promise/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/avatar.jpg">
      <meta itemprop="name" content="花猪">
      <meta itemprop="description" content="为了获得不同的阅读体验，建立此分站。<br>（可在导航栏搜索想要查看的文章）<br><br>本站主题：NEXT 8.6.1">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="花猪のBlog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Vue学习-Promise
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-08-17 15:08:43" itemprop="dateCreated datePublished" datetime="2021-08-17T15:08:43+08:00">2021-08-17</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-08-20 18:36:29" itemprop="dateModified" datetime="2021-08-20T18:36:29+08:00">2021-08-20</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/next/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" itemprop="url" rel="index"><span itemprop="name">学习笔记</span></a>
        </span>
    </span>

  
    <span id="/next/2021/08/17/Vue/Vue%E5%AD%A6%E4%B9%A0-Promise/" class="post-meta-item leancloud_visitors" data-flag-title="Vue学习-Promise" title="阅读次数">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span class="leancloud-visitors-count"></span>
    </span>
    <span id="/next/2021/08/17/Vue/Vue%E5%AD%A6%E4%B9%A0-Promise/" class="post-meta-item twikoo_visitors" data-flag-title="Vue学习-Promise" title="阅读次数">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="twikoo_visitors"></span>
    </span>
  
      </div>
      <div class="post-meta">
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>4.2k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>4 分钟</span>
    </span>
</div>

            <div class="post-description">本文将介绍Promise的使用</div>
        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>本文将介绍Promise的使用。</p>
<p>由于没有后端代码，对于ajax异步请求事件的实现就用<code>setTimeout()</code>函数代替：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;Hello World&#x27;</span>);</span><br><span class="line">&#125;, <span class="number">1000</span>)</span><br></pre></td></tr></table></figure>

<hr>
<h1 id="Promise"><a href="#Promise" class="headerlink" title="Promise"></a>Promise</h1><p>ES6提供了Promise对象。对于有异步请求的需求时，可以使用Promise对异步操作进行封装。其优势就是可以将异步操作以同步操作的流程表达出来，避免了层层嵌套的回调函数（“回调地狱”）。</p>
<h2 id="基本使用"><a href="#基本使用" class="headerlink" title="基本使用"></a>基本使用</h2><h3 id="创建"><a href="#创建" class="headerlink" title="创建"></a>创建</h3><p>可以直接使用new来调用Promise的构造器来进行实例化：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="comment">//异步处理代码</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<blockquote>
<p>说明：</p>
<p>Promise的参数为一个函数，该函数又会调用<code>resolve</code>或者<code>reject</code>函数</p>
</blockquote>
<h3 id="三种状态"><a href="#三种状态" class="headerlink" title="三种状态"></a>三种状态</h3><p>Promise 对象有三种状态：</p>
<ul>
<li>pending: 初始状态，不是成功或失败状态</li>
<li>fulfilled: 意味着操作成功完成</li>
<li>rejected: 意味着操作失败</li>
</ul>
<h3 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h3><p>当异步请求成功时，会调用<code>resolve</code>函数，其中该函数的参数即为请求的数据，在<code>Promise</code>对象的末尾可以接<code>promise.then()</code>函数，其中请求的数据可以被<code>then()</code>接收，进行处理：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> data = <span class="number">1</span>  <span class="comment">//为请求的参数</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    resolve(data)  <span class="comment">//当请求成功时调用resolve，并将data进行传递</span></span><br><span class="line">  &#125;,<span class="number">1000</span>)</span><br><span class="line">&#125;).then(<span class="function">(<span class="params">data</span>) =&gt;</span> &#123;  <span class="comment">//接收resolve传来的参数data</span></span><br><span class="line">  data = data + <span class="number">2</span>  <span class="comment">//对请求来的数据进行操作</span></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;参数接收并修改为：&#x27;</span> + data)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<img src="https://gitee.com/CNhuazhu/tu-chuang1/raw/master/img-blog/Promise-异步请求成功.png" style="zoom:80%;" />

<p>当异步请求失败时，会调用<code>reject</code>函数，该函数中的参数可以设置为一些错误信息，在<code>Promise</code>对象的末尾可以接<code>promise.catch()</code>函数，其中错误信息可以被<code>catch()</code>接收：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> data = <span class="number">1</span>  <span class="comment">//为请求的参数</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="comment">// resolve(data)  //当请求成功时调用resolve，并将data进行传递</span></span><br><span class="line"></span><br><span class="line">    reject(<span class="string">&#x27;未请求到数据&#x27;</span>)  <span class="comment">//当请求成功时调用reject，并将错误信息进行传递</span></span><br><span class="line">  &#125;,<span class="number">1000</span>)</span><br><span class="line">&#125;).then(<span class="function">(<span class="params">data</span>) =&gt;</span> &#123;  <span class="comment">//接收resolve传来的参数data</span></span><br><span class="line">  data = data + <span class="number">2</span>  <span class="comment">//对请求来的数据进行操作</span></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;参数接收并修改为：&#x27;</span> + data)</span><br><span class="line">&#125;).catch(<span class="function">(<span class="params">err</span>) =&gt;</span> &#123;  <span class="comment">//接收reject传来的参数（错误信息）</span></span><br><span class="line">  <span class="built_in">console</span>.log(err)  <span class="comment">//可以对该参数进行操作</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>此外，<code>promise.then()</code>函数可以同时接收两个参数，即<code>resolve</code>传递的请求数据以及<code>reject</code>传递的错误信息，因此可以使用以下格式简写：</p>
<p><code>new Promise((*resolve*, *reject*) *=&gt;* &#123;&#125;).then(*data* *=&gt;* &#123;&#125;, *err* *=&gt;* &#123;&#125;)</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> data = <span class="number">1</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    resolve(data)</span><br><span class="line">    reject(<span class="string">&#x27;未请求到数据&#x27;</span>)</span><br><span class="line">  &#125;, <span class="number">1000</span>)</span><br><span class="line">&#125;).then(<span class="function"><span class="params">data</span> =&gt;</span> &#123;</span><br><span class="line">  data = data + <span class="number">2</span></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;参数接收并修改为：&#x27;</span> + data)</span><br><span class="line">&#125;, <span class="function"><span class="params">err</span> =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(err)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="Promise的链式调用"><a href="#Promise的链式调用" class="headerlink" title="Promise的链式调用"></a>Promise的链式调用</h2><h3 id="链式调用"><a href="#链式调用" class="headerlink" title="链式调用"></a>链式调用</h3><p>无论是<code>promise.then()</code>函数还是<code>promise.catch()</code>函数，都可以返回一个<code>Promise</code>对象。基于此可以实现链式调用，以处理不同的异步请求。这便是Promise的优势，在实现层层嵌套的回调函数（请求）的同时又不失代码格式的整洁：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> data = <span class="number">1</span>  <span class="comment">//初次请求的数据</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    resolve(data)  <span class="comment">//第一次网络请求</span></span><br><span class="line">    <span class="comment">// reject(&#x27;请求数据失败&#x27;)</span></span><br><span class="line">  &#125;, <span class="number">1000</span>)</span><br><span class="line">&#125;).then(<span class="function">(<span class="params">data2</span>) =&gt;</span> &#123;  <span class="comment">//接收上层resolve传来的数据（data）</span></span><br><span class="line">  data2 = data2 + <span class="number">1</span>  <span class="comment">//第一次处理请求</span></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;处理第一次请求数据，将其改为：&#x27;</span> + data2)</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;  <span class="comment">//返回一个新的Promise对象</span></span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">      resolve(data2)  <span class="comment">//第二次网络请求</span></span><br><span class="line">      <span class="comment">// reject(&#x27;请求数据失败&#x27;)</span></span><br><span class="line">    &#125;, <span class="number">1000</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;).then(<span class="function">(<span class="params">data3</span>) =&gt;</span> &#123;  <span class="comment">//接收上层resolve传来的数据（data2）</span></span><br><span class="line">  data3 = data3 + <span class="number">1</span>  <span class="comment">//第二次处理请求</span></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;处理第二次请求数据，将其改为：&#x27;</span> + data3)</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;  <span class="comment">//返回一个新的Promise对象</span></span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">      resolve(data3)  <span class="comment">//第三次网络请求</span></span><br><span class="line">      <span class="comment">// reject(&#x27;请求数据失败&#x27;)</span></span><br><span class="line">    &#125;, <span class="number">1000</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;).then(<span class="function">(<span class="params">data4</span>) =&gt;</span> &#123;  <span class="comment">//接收上层resolve传来的数据（data3）</span></span><br><span class="line">  data4 = data4 + <span class="number">1</span>  <span class="comment">//第三次处理请求</span></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;处理第三次请求数据，将其改为：&#x27;</span> + data4)</span><br><span class="line">&#125;).catch(<span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(err)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>运行结果如下：</p>
<img src="https://gitee.com/CNhuazhu/tu-chuang1/raw/master/img-blog/Promise-链式编程.png" style="zoom:80%;" />

<blockquote>
<p>说明：</p>
<p>可以在任意位置调用<code>promise.catch()</code>函数进行错误捕获，一旦在这函数之前的“链”中有异步请求错误，都会捕捉到这一信息。</p>
</blockquote>
<h3 id="简写一"><a href="#简写一" class="headerlink" title="简写一"></a>简写一</h3><p><code>new Promise(resolve =&gt; resolve(结果))</code>可以简写：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> data = <span class="number">1</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    resolve(data)</span><br><span class="line">  &#125;, <span class="number">1000</span>)</span><br><span class="line">&#125;).then(<span class="function">(<span class="params">data2</span>) =&gt;</span> &#123;</span><br><span class="line">  data2 = data2 + <span class="number">1</span></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;处理第一次请求数据，将其改为：&#x27;</span> + data2)</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Promise</span>.resolve(data2)</span><br><span class="line">  <span class="comment">// throw &#x27;请求异常&#x27;</span></span><br><span class="line">&#125;).then(<span class="function">(<span class="params">data3</span>) =&gt;</span> &#123;</span><br><span class="line">  data3 = data3 + <span class="number">1</span></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;处理第二次请求数据，将其改为：&#x27;</span> + data3)</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">Promise</span>.resolve(data3)</span><br><span class="line">  <span class="comment">// throw &#x27;请求异常&#x27;</span></span><br><span class="line">&#125;).then(<span class="function">(<span class="params">data4</span>) =&gt;</span> &#123;</span><br><span class="line">  data4 = data4 + <span class="number">1</span></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;处理第三次请求数据，将其改为：&#x27;</span> + data4)</span><br><span class="line">  <span class="comment">// throw &#x27;请求异常&#x27;</span></span><br><span class="line">&#125;).catch(<span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(err)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<blockquote>
<p>说明：</p>
<p>可以在新的请求后添加<code>throw</code>关键词，以将错误信息抛出，最后可以用<code>promise.catch()</code>函数进行捕获。</p>
</blockquote>
<h3 id="简写二"><a href="#简写二" class="headerlink" title="简写二"></a>简写二</h3><p>可以进一步把<code>Promise.resolve()</code>省略：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> data = <span class="number">1</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    resolve(data)</span><br><span class="line">  &#125;, <span class="number">1000</span>)</span><br><span class="line">&#125;).then(<span class="function">(<span class="params">data2</span>) =&gt;</span> &#123;</span><br><span class="line">  data2 = data2 + <span class="number">1</span></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;处理第一次请求数据，将其改为：&#x27;</span> + data2)</span><br><span class="line">  <span class="keyword">return</span> data2</span><br><span class="line">  <span class="comment">// throw &#x27;请求异常&#x27;</span></span><br><span class="line">&#125;).then(<span class="function">(<span class="params">data3</span>) =&gt;</span> &#123;</span><br><span class="line">  data3 = data3 + <span class="number">1</span></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;处理第二次请求数据，将其改为：&#x27;</span> + data3)</span><br><span class="line">  <span class="keyword">return</span> data3</span><br><span class="line">  <span class="comment">// throw &#x27;请求异常&#x27;</span></span><br><span class="line">&#125;).then(<span class="function">(<span class="params">data4</span>) =&gt;</span> &#123;</span><br><span class="line">  data4 = data4 + <span class="number">1</span></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">&#x27;处理第三次请求数据，将其改为：&#x27;</span> + data4)</span><br><span class="line">  <span class="comment">// throw &#x27;请求异常&#x27;</span></span><br><span class="line">&#125;).catch(<span class="function">(<span class="params">err</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(err)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<blockquote>
<p>说明：</p>
<p><code>return</code>默认返回的数据可以作为新的请求。</p>
</blockquote>
<hr>
<h1 id="后记"><a href="#后记" class="headerlink" title="后记"></a>后记</h1><p>为了更好的理解axios。</p>

    </div>

    
    
    
      
  <div class="popular-posts-header">相关文章</div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\next\2021\08\02\Vue\Vue学习笔记\" rel="bookmark">Vue学习笔记</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\next\2021\08\19\Vue\Vue学习-axios\" rel="bookmark">Vue学习-axios</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\next\2021\08\17\Vue\Vue学习-Vuex\" rel="bookmark">Vue学习-Vuex</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\next\2021\08\14\Vue\Vue学习-Vue-router\" rel="bookmark">Vue学习-Vue router</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\next\2021\08\13\Vue\Vue学习-Vue-cli\" rel="bookmark">Vue学习-Vue CLI</a></div>
    </li>
  </ul>


    <footer class="post-footer">
          <div class="reward-container">
  <div></div>
  <button>
    赞赏
  </button>
  <div class="post-reward">
      <div>
        <img src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/wechat.png" alt="花猪 微信">
        <span>微信</span>
      </div>
      <div>
        <img src="https://cdn.jsdelivr.net/gh/CNhuazhu/Image/alipay.jpg" alt="花猪 支付宝">
        <span>支付宝</span>
      </div>

  </div>
</div>

          <div class="post-tags">
              <a href="/next/tags/Vue/" rel="tag"><i class="fa fa-tag"></i> Vue</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/next/2021/08/14/Vue/Vue%E5%AD%A6%E4%B9%A0-Vue-router/" rel="prev" title="Vue学习-Vue router">
                  <i class="fa fa-chevron-left"></i> Vue学习-Vue router
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/next/2021/08/17/Vue/Vue%E5%AD%A6%E4%B9%A0-Vuex/" rel="next" title="Vue学习-Vuex">
                  Vue学习-Vuex <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






    <div class="comments"><div id="twikoo-comments"></div></div>
</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">花猪</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">356k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">5:23</span>
  </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@next-theme/pjax@0.5.0/pjax.min.js" integrity="sha256-3NkoLDrmHLTYj7csHIZSr0MHAFTXth7Ua/DDt4MRUAg=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js" integrity="sha256-yt2kYMy0w8AbtF89WXb2P1rfjcP/HTHLT7097U8Y5b8=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/medium-zoom@1.0.6/dist/medium-zoom.min.js" integrity="sha256-EdPgYcPk/IIrw7FYeuJQexva49pVRZNmt3LculEr7zM=" crossorigin="anonymous"></script>
<script src="/next/js/comments.js"></script><script src="/next/js/utils.js"></script><script src="/next/js/motion.js"></script><script src="/next/js/schemes/muse.js"></script><script src="/next/js/next-boot.js"></script><script src="/next/js/pjax.js"></script>

  
<script src="/next/js/third-party/search/local-search.js"></script>




  


  <script class="next-config" data-name="leancloud_visitors" type="application/json">{"enable":true,"app_id":"dh8GVAcIwU1TN4zhA5y63iW1-gzGzoHsz","app_key":"hzyAqDKjG4OBGrdPS7mKaOa7","server_url":null,"security":true}</script>
  <script src="/next/js/third-party/statistics/lean-analytics.js"></script>


  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://cdn.jsdelivr.net/npm/mathjax@3.2.0/es5/tex-mml-chtml.js","integrity":"sha256-r+3itOMtGGjap0x+10hu6jW/gZCzxHsoKrOd7gyRSGY="}}</script>
<script src="/next/js/third-party/math/mathjax.js"></script>


<script class="next-config" data-name="twikoo" type="application/json">{"enable":true,"visitor":true,"envId":"hexo-1g41404w9f800e94","el":"#twikoo-comments"}</script>
<script>
document.addEventListener('page:loaded', () => {
  NexT.utils.loadComments(CONFIG.twikoo.el)
    .then(() => NexT.utils.getScript(
      'https://cdn.jsdelivr.net/npm/twikoo/dist/twikoo.all.min.js',
      { condition: window.twikoo }
    ))
    .then(() => {
      twikoo.init(CONFIG.twikoo);
    });
});
</script>

</body>
</html>
